/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.controller;

import io.renren.service.SysGeneratorService;
import io.renren.service.excel.GeneratorMysqlFromExcelService;
import io.renren.utils.PageUtils;
import io.renren.utils.Query;
import io.renren.utils.R;
import io.renren.utils.RRException;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 代码生成器
 * 
 * @author Mark
 */
@Controller
@RequestMapping("/excel/data/generatormysql")
public class GeneratorMysqlFromExcelController {
	@Autowired
	private GeneratorMysqlFromExcelService generatorMysqlFromExcelService;

	@ResponseBody
	@RequestMapping("/code")
	public String code(@RequestParam("file") MultipartFile file,@RequestParam("tableName") String tableName,HttpServletResponse response) throws Exception {
		String result=generatorMysqlFromExcelService.GeneratorMysqlFromExcel(file, tableName);
		return result;
	}
	
	@ResponseBody
	@RequestMapping("/zip")
	public String codewithzip(@RequestParam("file") MultipartFile file,@RequestParam("tableName") String tableName,HttpServletResponse response) throws Exception {
		String result=generatorMysqlFromExcelService.GeneratorMysqlFromExcel(file, tableName);
		String fileName="由"+file.getName()+"生成的"+tableName+".sql";
		byte[] data = generatorMysqlFromExcelService.GeneratorMysqlFromExcelZip(result, fileName);
		response.reset();
		response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".zip");
		response.addHeader("Content-Length", "" + data.length);
		response.setContentType("application/octet-stream; charset=UTF-8");
		IOUtils.write(data, response.getOutputStream());
		return result;
	}
	
}
